﻿// // ******************************************************************
// //       /\ /|       @file       JellyfinUserQueryHandler.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-11 19:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-10 14:11 Await
// // ******************************************************************

using AutomaticSubtitles.Service.Application.Config.Commands;
using AutomaticSubtitles.Service.Application.Jellyfin.Queries.User;
using AutomaticSubtitles.Service.Domain.Config;

namespace AutomaticSubtitles.Service.Application.Jellyfin;

public class JellyfinUserQueryHandler(IConfigDataRepository repository, IHttpClientFactory httpClientFactory) : BaseAutoService
{
    [EventHandler]
    public async Task Handle(GetJellyfinUserViewsQuery query)
    {
        var autoConfig = await repository.FindAsync(x => x.Id == query.id);
        IsDataNotExist(autoConfig);
        var autoConfigUserId = autoConfig.UserId;
        if (autoConfigUserId.IsNullOrWhiteSpace())
        {
            var commd = new UpdateConfigTokenCommand(autoConfig.Id);
            await PublishAsync(commd);
            autoConfigUserId = commd.Result;
        }

        IsDataNotExist(autoConfigUserId);
        var jellyfinUserViewsDto = await JellyfinHelper.UserViews(httpClientFactory, autoConfig.Token, autoConfigUserId, autoConfig.ServerUrl);
        query.Result = jellyfinUserViewsDto;
    }
}